import React, { use, useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import './StockChart.css';

//组件的接口使用的是后端的数据结构，然后传送到这里自己分解成echarts的数据结构，再进行渲染
const StockChart = ({tickData,dayKdata,weekKdata,monthKdata,infoData,stockCode,isDataLoaded}) => {

  const mainChartRef = useRef(null);
  const volumeChartRef = useRef(null);
  const mainChartInstance = useRef(null);
  const volumeChartInstance = useRef(null);

  const chartWrapperRef = useRef(null);
  const [currentChartType, setCurrentChartType] = useState('1day');
  const [tooltipData, setTooltipData] = useState(null);
  const [crosshairPosition, setCrosshairPosition] = useState(null);
  const [timeChartData, setTimeChartData] = useState(null);
  const timeChartDataRef = useRef(timeChartData);
  const [tickDataOuter, setTickDataOuter] = useState(null);
  const [kChartData, setKChartData] = useState(null);
  const [dayKData, setDayKData] = useState(null);
  const [weekKData, setWeekKData] = useState(null);
  const [monthKData, setMonthKData] = useState(null);
  const [stockInfo, setStockInfo] = useState({
    ts_code: '-' ,
    name: '-' ,
    close: '-' ,
    pct_chg: 0,
    amount: 0,
    turnover_rate_f: 0,
    volume_ratio: 0,
    circ_mv: 0,
    float_share: 0,
    total_mv: 0,
    total_share: 0,
    industry: '-' ,
    area: '-' ,
    is_hs:'-' ,
    pe:0,
    pb:0,
    dv_ratio:0,
  });

  useEffect(() => {
    // 初始化图表
    if (mainChartRef.current) {
      // 如果已经有实例，先销毁
      if (mainChartInstance.current) {
        mainChartInstance.current.dispose();
      }
      // 创建新实例
      mainChartInstance.current = echarts.init(mainChartRef.current);
    }
    if(volumeChartRef.current)
    {
      if (volumeChartInstance.current) {
        volumeChartInstance.current.dispose();
      }
      volumeChartInstance.current = echarts.init(volumeChartRef.current);
    }

    // if(isDataLoaded)
    // {
      renderChart();
    // }
    if(tickData && tickData.data && tickData.data.length > 0)
    {
      const tickDataCopy = JSON.parse(JSON.stringify(tickData));
      setTickDataOuter(tickDataCopy)
    }
    
    
    // 组件卸载时销毁图表
    return () => {
      if (mainChartInstance.current) {
        mainChartInstance.current.dispose();
      }
    };
  }, [stockCode, tickData,dayKdata,currentChartType,isDataLoaded]);
  
  // 窗口大小变化时，重新调整图表大小
  useEffect(() => {
    const handleResize = () => {
      if (mainChartInstance.current) {
        mainChartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

    // 同步更新 timeChartDataRef
  useEffect(() => {
    timeChartDataRef.current = timeChartData;
  }, [timeChartData]);

  
  
  useEffect(() => {
    if(dayKdata && dayKdata.dates && dayKdata.dates.length > 0)
    {
      setDayKData(dayKdata)
      console.log('dayKdata = ',dayKdata)
    }
  },[dayKdata])

  useEffect(() => {
    if(weekKdata && weekKdata.dates && weekKdata.dates.length > 0)
    {
      setWeekKData(weekKdata)
    }
  },[weekKdata])

  useEffect(() => {
    if(monthKdata && monthKdata.dates && monthKdata.dates.length > 0)
    {
      setMonthKData(monthKdata)
    }
  },[monthKdata])

  // 确保 infoData 变化时更新右侧信息区域的数据
  useEffect(() => {
    if (infoData) {
      const formattedData = {
        ...infoData,
        pct_chg: `${(infoData.pct_chg).toFixed(2)}%`,
        amount: (infoData.amount / 100000).toFixed(1) + '亿元',
        turnover_rate_f: `${(infoData.turnover_rate_f).toFixed(2)}%`,
        volume_ratio: `${(infoData.volume_ratio).toFixed(2)}`,
        circ_mv: (infoData.circ_mv / 10000).toFixed(1) + '亿',
        total_mv: (infoData.total_mv / 10000).toFixed(1) + '亿',
        is_hs: infoData.is_hs === 'N' ? '否' : infoData.is_hs === 'H' ? '沪股通' : '深股通',
        pe: (infoData.pe).toFixed(2),
        pb: (infoData.pb).toFixed(2),
        dv_ratio: (infoData.dv_ratio).toFixed(2),
      };
      setStockInfo(formattedData);
    }
    // console.log('infoData', infoData);
  }, [infoData]);

  // 初始化图表
  useEffect(() => {
    const mainChart = echarts.init(mainChartRef.current);
    const volumeChart = echarts.init(volumeChartRef.current);
    
    // 添加 resize 事件监听
    const handleResize = () => {
      mainChart.resize();
      volumeChart.resize();
    };
    
    // 配置时间轴
    const timeAxisOption = {
      xAxis: {
        type: 'category',
        data: tickData?.data?.map(item => item.time),
        axisLabel: {
          formatter: function (value) {
            const date = new Date(value);
            return `${date.getMonth() + 1}/${date.getDate()}`;
          }
        }
      }
    };
    mainChart.setOption(timeAxisOption);
    // window.addEventListener('resize', handleResize);
    // 鼠标移动事件处理
  
    if(!isDataLoaded || !tickData || !tickData.data || tickData.data.length === 0)
    {
      // 移除已绑定的鼠标事件（如果存在）
      mainChartRef.current.removeEventListener('mousemove', handleChartMouseMove);
      mainChartRef.current.removeEventListener('mouseleave', handleChartMouseLeave);
      return;
    }
    // 清除旧图表
    // mainChart.clear();
    // volumeChart.clear();
    //强制触发 resize 事件，确保宽度一致
    setTimeout(() => {
      mainChart.resize();
      volumeChart.resize();
    }, 0);
    // 基准价格
    console.log('tickData',tickData)
    // 深拷贝 tickData，避免修改原始数据



    // 清理函数
    return () => {
      mainChartRef.current?.removeEventListener('mousemove', handleChartMouseMove);
      mainChartRef.current?.removeEventListener('mouseleave', handleChartMouseLeave);
      window.removeEventListener('resize', handleResize);
      mainChart.dispose();
      volumeChart.dispose();
    };
  }, [currentChartType,stockCode,isDataLoaded]);

  //以下为各种函数定义部分
  const calculateMA = (data,dayCount) => {
    const result = [];
    if (!data || data.length === 0) return result;
    
    for (let i = 0; i < data.length; i++) {
      if (i < dayCount - 1) {
        result.push('-');
        continue;
      }
      let sum = 0;
      let validDays = 0;
      for (let j = 0; j < dayCount; j++) {
        if (i - j >= 0 && data[i - j] && typeof data[i - j].close === 'number') {
          sum += data[i - j].close;
          validDays++;
        }
      }
      result.push(validDays > 0 ? sum / validDays : '-');
    }
    return result;
  };


  // 主要功能部分：根据当前图表类型渲染
  const renderChart = () => {
    if (currentChartType === '1day' || currentChartType === '5day') {
      document.getElementById('change-labels').style.display = 'flex';//左侧有标签
      renderTimeChart();
    } else {
      document.getElementById('change-labels').style.display = 'none';//左侧没有标签
      renderKChart(currentChartType);
    }
  };



  //适用于日、周、月k线数据的转换
  const convertDayKData = (kdata) => {
    const data = [];
    const volumes = [];

    if(kdata && kdata.dates && kdata.dates.length > 0)
    {
      let kdataLen = kdata.dates.length;

      for (let i = 0; i < kdataLen; i++) {
        let open = kdata.candles[i].open;
        let close = kdata.candles[i].close;
        let low = kdata.candles[i].low;
        let high = kdata.candles[i].high;
        let amount = kdata.candles[i].amount;

        data.push({
          time: kdata.dates[i],
          value: [open, close, low, high],
          amount: amount,
          open: open,
          itemStyle: close >= open ? {
            color: 'transparent',
            borderColor: '#ff0000',
            borderWidth: 2
          } : {}
        });
        // // K线图成交量颜色根据涨跌显示
        const color = close >= open ? '#ff0000' : '#00ff00';
        volumes.push({
          value: amount,
          itemStyle: close >= open ? {
            color: 'transparent',
            borderColor: color,
            borderWidth: 2
          } : { color }
        });
      }
      // // 计算均线数据
      const ma5 = calculateMA(kdata.candles,5)
      const ma10 = calculateMA(kdata.candles,10)
      const ma20 = calculateMA(kdata.candles,20)
      const ma60 = calculateMA(kdata.candles,60)
      
      return { data, volumes, ma5, ma10, ma20, ma60 };  
    }
    return { data, volumes, ma5:[], ma10:[], ma20:[], ma60:[] };  
      
  };
    // 更新分时图标签.minPrice：最低价，maxPrice：最高价，maxChange：最大涨幅，volumes：成交量数组，times：时间数组
    const updateTimeLabels = (minPrice, maxPrice, maxChange, pre_close,volumes, times) => {
      const priceLabels = document.getElementById('price-labels');
      const changeLabels = document.getElementById('change-labels');
      const volumeLabels = document.getElementById('volume-labels');
      const priceStepNum = 4;//大图使用9个区间，小图使用4个区间 
      
      if (priceLabels && changeLabels && volumeLabels) {
        priceLabels.innerHTML = '';
        changeLabels.innerHTML = '';
        volumeLabels.innerHTML = '';
        
        // 检查数据有效性
        if (!times || !volumes || times.length === 0 || volumes.length === 0) {
          console.warn('Invalid or empty data in updateTimeLabels');
          return;
        }

        // 计算最大涨幅和最大跌幅
        const priceStep = (maxPrice - minPrice) / (priceStepNum*2); // 上下各4个区间

        //从上到下（价格标签，右侧）
        for (let i = priceStepNum; i >= -priceStepNum; i--) {
          const price = pre_close + i * priceStep;
          const priceElement = document.createElement('div');
          priceElement.textContent = price.toFixed(2);
          priceElement.className = i === 0 ? 'zero-axis' : (i > 0 ? 'positive' : 'negative');
          priceLabels.appendChild(priceElement);
        }
        
        // 分时图涨跌幅标签（左侧）- 零轴上下各分为9个区间
        const changeRange = maxChange * 100;
        const changeStep = changeRange / priceStepNum;
        const labelHeight = 100 / (priceStepNum * 2); // 计算每个标签的高度百分比
        for (let i = priceStepNum; i >= -priceStepNum; i--) {
          const changePercent = i * changeStep;
          const changeElement = document.createElement('div');
          changeElement.textContent = changePercent.toFixed(2) + '%';
          changeElement.className = i === 0 ? 'zero-axis' : (i > 0 ? 'positive' : 'negative');
          // changeElement.style.position = 'absolute';
          // changeElement.style.top = `${50 + (i * labelHeight)}%`; // 动态计算位置
          // changeElement.style.transform = 'translateY(-50%)';
          changeLabels.appendChild(changeElement);
        }
        
        
        // 成交量标签（左侧）- 4个标签
        const maxVolume = Math.max(...volumes.map(v => v.value));
        const volumeStep = maxVolume / 3;
        for (let i = 3; i >= 0; i--) {
          const volume = i * volumeStep;
          const volumeElement = document.createElement('div');
          volumeElement.textContent = (volume / 10000).toFixed(1) + '万';
          volumeElement.style.color = '#ccc';
          volumeLabels.appendChild(volumeElement);
        }
      }
    };
    // 生成分时图网格配置
    const generateTimeGridLines = (minPrice, maxPrice, pre_close) => {
      const priceStepNum = 4;//大图使用9个区间，小图使用4个区间 
      const gridLines = [];
      const maxDiff = Math.max(Math.abs(minPrice - pre_close),Math.abs(maxPrice - pre_close))
      const priceStep = maxDiff / priceStepNum; // 9个区间
      
      // 生成9条水平网格线
      for (let i = 0; i <= priceStepNum*2; i++) {
        const price = pre_close -1.0 * maxDiff + i * priceStep;
        // console.log('price = ',price,basePrice)
        const isZeroLine = Math.abs(price - pre_close) < priceStep * 0.1;
        
        gridLines.push({
          y: price,
          lineStyle: {
            color: isZeroLine ? '#ff0000' : 'rgba(255, 0, 0, 0.3)',
            width: isZeroLine ? 2 : 1,
            type: isZeroLine ? 'solid' : 'dashed'
          }
        });
      }
      console.log('gridLines',gridLines)
      return gridLines;
    };
    // 生成时间网格线
    const generateTimeGridLinesVertical = (times) => {
      if (!times || times.length === 0) return [];
      const interval = Math.floor(times.length / 4);
      const gridLines = [];
      for (let i = 1; i < 4; i++) {
        const timeIndex = i * interval;
        if (timeIndex < times.length) {
          gridLines.push({
            // type: 'line',
            // xAxisIndex: 0,
            // yAxisIndex: 0,
            lineStyle: {
              color: '#ff0000',
              type: 'dashed',
              width: 1
            },
            x: times[timeIndex]
          });
        }
      }
      console.log('gridLines vertical',gridLines)
      return gridLines;
    };

    // 更新K线图标签
    const updateKLineLabels = (minPrice, maxPrice, volumes) => {
      const priceLabels = document.getElementById('price-labels');
      const changeLabels = document.getElementById('change-labels');
      const volumeLabels = document.getElementById('volume-labels');
      
      if (priceLabels && changeLabels && volumeLabels) {
        priceLabels.innerHTML = '';
        changeLabels.innerHTML = '';
        volumeLabels.innerHTML = '';
        
        // K线图价格标签（右侧）- 全部红色
        const priceStep = (maxPrice - minPrice) / 5;
        for (let i = 5; i >= 0; i--) {
          const price = minPrice + i * priceStep;
          const priceElement = document.createElement('div');
          priceElement.textContent = price.toFixed(2);
          priceElement.style.color = '#ff0000';
          priceLabels.appendChild(priceElement);
        }
        
        // K线图不显示涨跌幅标签
        changeLabels.style.display = 'none';
        
        // K线图成交金额标签（右侧）- 2个标签
        const maxAmount = Math.max(...volumes.map(v => v.value));
        const amountStep = maxAmount / 1;
        for (let i = 1; i >= 0; i--) {
          const amount = i * amountStep;
          const amountElement = document.createElement('div');
          amountElement.textContent = (amount / 100000000).toFixed(0) + '亿';
          amountElement.style.color = '#ccc';
          volumeLabels.appendChild(amountElement);
        }
      }
    };

    // 生成K线图网格配置
    const generateKGridLines = (minPrice, maxPrice) => {
      const gridLines = [];
      const priceStep = (maxPrice - minPrice) / 7; // 6个网格
      
      // 生成6条水平网格线
      for (let i = 0; i < 7; i++) {
        const price = minPrice + i * priceStep;
        gridLines.push({
          y: price,
          lineStyle: {
            color: 'rgba(255, 0, 0, 0.3)',
            type: 'dashed',
            width: 1
          }
        });
      }
      
      return gridLines;
    };

    // 生成分时图成交量网格配置
    const generateTimeVolumeGridLines = (maxVolume) => {
      const gridLines = [];
      const volumeStep = maxVolume / 3; // 4个区间
      
      // 生成4条水平网格线
      for (let i = 0; i <= 3; i++) {
        const volume = i * volumeStep;
        gridLines.push({
          y: volume,
          lineStyle: {
            color: 'rgba(255, 0, 0, 0.3)',
            type: 'dashed',
            width: 1
          }
        });
      }
      
      return gridLines;
    };
  
    // 绘制分时图
    const renderTimeChart = () => {
      console.log('renderTimeChart stockCode = ',stockCode)
      let chartDataDict = {}
      if (currentChartType === '1day') {
        chartDataDict = convertTimeData('1day')
      }
      else if (currentChartType === '5day') {
        chartDataDict = convertTimeData('5day')
      }
      const { times = [], data = [], avgData = [], volumes = [], pre_close } = chartDataDict;
      setTimeChartData(chartDataDict)
      // 添加鼠标事件监听
      // 确保数据加载完成后再绑定事件
      if (times && times.length > 0) {
        mainChartRef.current.addEventListener('mousemove', handleChartMouseMove);
        mainChartRef.current.addEventListener('mouseleave', handleChartMouseLeave);
      }
      // 修复鼠标位置与十字星位置不重叠的问题

      
      if (!Array.isArray(times) || !Array.isArray(data) || !Array.isArray(avgData) || !Array.isArray(volumes)) {
        console.error('Invalid data format for time chart');
        return;
      }
      
      const priceChanges = data.map(price => Math.abs(price - pre_close) / pre_close);
      const maxChange = Math.max(...priceChanges);
      const maxPrice = pre_close * (1 + maxChange);
      const minPrice = pre_close * (1 - maxChange);

      const maxVolume = volumes.length > 0 ? Math.max(...volumes.map(v => v.value)) : 0;

      
      updateTimeLabels( minPrice, maxPrice,maxChange,pre_close,volumes, times);
      
      // 生成网格线
      const gridLines = generateTimeGridLines(minPrice, maxPrice, pre_close);
      const volumeGridLines = generateTimeVolumeGridLines(maxVolume);
       // 应用网格线到图表
      const gridLinesVertical = generateTimeGridLinesVertical(times);

      
      // 主图配置
      const mainOption = {
        backgroundColor: '#000000',
        animation: false,
        grid: {
          left: 5,
          right: 5,
          top: 10,
          bottom: 5,
          containLabel: false,
          backgroundColor: '#000000'
        },
        xAxis: {
          type: 'category',
          data: times,
          show: false,
          boundaryGap: false,
          axisLine: {
            show: true,
          },
        },
        yAxis: {
          type: 'value',
          scale: true,
          show: true,
          min: minPrice,
          max: maxPrice,
          splitLine: { show: false }
        },
        series: [
          {
            name: '分时',
            type: 'line',
            data: data,
            smooth: true,
            lineStyle: {
              color: '#FFFFFF',
              width: 2
            },
            itemStyle: {
              color: '#FFFFFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255, 255, 255, 0.3)' },
                { offset: 1, color: 'rgba(255, 255, 255, 0.05)' }
              ])
            },
            symbol: 'none'
          },
          {
            name: '均价',
            type: 'line',
            data: avgData,
            smooth: true,
            lineStyle: {
              color: '#FFFF00',
              width: 1
            },
            itemStyle: {
              color: '#FFFF00'
            },
            symbol: 'none'
          }
        ]
      };
      
      // 手动添加主图网格线
      gridLines.forEach((gridLine) => {
        mainOption.series.push({
          type: 'line',
          data: times.map(() => gridLine.y),
          lineStyle: gridLine.lineStyle,
          symbol: 'none',
          animation: false
        });
      });

      // 手动添加主图网格线
      gridLinesVertical.forEach((gridLine) => {
        mainOption.series.push({
          type: 'line',
          data: times.map(() => gridLine.y),
          lineStyle: gridLine.lineStyle,
          symbol: 'none',
          animation: false
        });
      });
      
      // 成交量图配置
      const volumeOption = {
        backgroundColor: '#000000',
        animation: false,
        grid: {
          left: 5,
          right: 5,
          top: 5,
          bottom: 5,
          containLabel: false,
          backgroundColor: '#000000'
        },
        xAxis: {
          type: 'category',
          data: times,
          axisLine: { 
            show: true,
            lineStyle: { color: '#666' }
          },
          axisTick: { show: false },
          axisLabel: { 
            show: true, 
            fontSize: 10,
            color: '#ccc'
          },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          show: false,
          min: 0,
          max: maxVolume,
          splitLine: { show: false }
        },
        series: [
          {
            name: '成交量',
            type: 'bar',
            data: volumes,
            barWidth: '60%'
          }
        ]
      };
      
      // 手动添加成交量网格线
      volumeGridLines.forEach((gridLine) => {
        volumeOption.series.push({
          type: 'line',
          data: times.map(() => gridLine.y),
          lineStyle: gridLine.lineStyle,
          symbol: 'none',
          animation: false
        });
      });
      if(mainChartInstance.current)
      {
          mainChartInstance.current.clear()
          mainChartInstance.current.setOption(mainOption,true);
      }
      if(volumeChartInstance.current)
      {
          volumeChartInstance.current.clear()

          volumeChartInstance.current.setOption(volumeOption,true);
      }
      // 手动触发 resize
      // setTimeout(() => {
      //   mainChartRef.resize();
      //   volumeChartRef.resize();
      // }, 0);
    };

    // 绘制K线图
    const renderKChart = (period) => {
      let kdata;
      if(period === 'day')
      {
        kdata = dayKData
      }
      if(period === 'week')
      {
          kdata = weekKData
      }
      else if(period === 'month')
      {
          kdata = monthKData
      }
      const { data, volumes, ma5, ma10, ma20, ma60 } = convertDayKData(kdata);
      
      const prices = data.flatMap(item => item.value);
      const minPrice = Math.min(...prices);
      const maxPrice = Math.max(...prices);
      
      updateKLineLabels(minPrice, maxPrice, volumes);
      
      // 生成网格线
      const gridLines = generateKGridLines(minPrice, maxPrice);
      
      const dates = data.map(item => {
        const date = new Date(item.time);
        if (period === 'day') {
          return echarts.time.format(date, '{MM}/{dd}', false);
        } else if (period === 'week') {
          return echarts.time.format(date, '{MM}/{dd}', false);
        } else {
          return echarts.time.format(date, '{yyyy}/{MM}', false);
        }
      });
      
      // 主图配置
      const mainOption = {
        backgroundColor: '#000000',
        animation: false,
        grid: {
          left: 5,
          right: 5,
          top: 10,
          bottom: 5,
          containLabel: false,
          backgroundColor: '#000000'
        },
        xAxis: {
          type: 'category',
          data: dates,
          show: false,
          boundaryGap: false,
        },
        yAxis: {
          type: 'value',
          scale: true,
          show: false,
          min: minPrice,
          max: maxPrice,
          splitLine: { show: false }
        },
        series: [
          {
            name: 'K线',
            type: 'candlestick',
            data: data.map(item => item.value),
            itemStyle: {
              color: 'transparent',
              color0: '#43b5d5',
              borderColor: '#ff0000',
              borderColor0: '#5daed3ff',
              borderWidth: 2
            }
          },
          {
            name: 'MA5',
            type: 'line',
            data: ma5,
            smooth: true,
            lineStyle: {
              color: '#FFFF00',
              width: 1
            },
            symbol: 'none'
          },
          {
            name: 'MA10',
            type: 'line',
            data: ma10,
            smooth: true,
            lineStyle: {
              color: '#00FF00',
              width: 1
            },
            symbol: 'none'
          },
          {
            name: 'MA20',
            type: 'line',
            data: ma20,
            smooth: true,
            lineStyle: {
              color: '#FF00FF',
              width: 1
            },
            symbol: 'none'
          },
          {
            name: 'MA60',
            type: 'line',
            data: ma60,
            smooth: true,
            lineStyle: {
              color: '#00FFFF',
              width: 1
            },
            symbol: 'none'
          }
        ],
        dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0, 1], // 绑定到K线图和成交量区域的xAxis
          start: 0,
          end: 100,
          zoomOnMouseWheel: true,
          moveOnMouseMove: true,
          onZoom: (params) => {
            console.log('onZoom triggered:', params);
            const { startValue, endValue } = params;
            const currentData = data.slice(startValue, endValue + 1);
            const currentPrices = currentData.flatMap(item => item.value);
            const currentMinPrice = Math.min(...currentPrices);
            const currentMaxPrice = Math.max(...currentPrices);
            const currentVolumes = volumes.slice(startValue, endValue + 1);
            const currentMaxVolume = Math.max(...currentVolumes);
            
            console.log('Current price range:', currentMinPrice, currentMaxPrice);
            console.log('Current max volume:', currentMaxVolume);
            
            mainChartInstance.current.setOption({
              yAxis: {
                min: currentMinPrice,
                max: currentMaxPrice
              }
            });
            
            volumeChartInstance.current.setOption({
              yAxis: {
                max: currentMaxVolume
              }
            });
          }
        },
        {
          show: true,
          type: 'slider',
          xAxisIndex: [0, 1], // 绑定到K线图和成交量区域的xAxis
          start: 0,
          end: 100,
          top: '97%',
          height: 20,
          borderColor: '#555',
          fillerColor: 'rgba(80,80,80,0.5)',
          textStyle: {
            color: '#ccc'
          }
        }
      ],
      // console.log('dataZoom configuration applied');
      };
      
      // 手动添加主图网格线
      gridLines.forEach((gridLine) => {
        mainOption.series.push({
          type: 'line',
          data: dates.map(() => gridLine.y),
          lineStyle: gridLine.lineStyle,
          symbol: 'none',
          animation: false
        });
      });
      
      // 成交量图配置
      const volumeOption = {
        backgroundColor: '#000000',
        animation: false,
        grid: {
          left: 5,
          right: 5,
          top: 5,
          bottom: 5,
          containLabel: false,
          backgroundColor: '#000000'
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLine: { 
            show: true,
            lineStyle: { color: '#666' }
          },
          axisTick: { show: false },
          axisLabel: { 
            show: true, 
            fontSize: 10,
            color: '#ccc'
          },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          show: false,
          splitLine: { show: false }
        },
        series: [
          {
            name: '成交量',
            type: 'bar',
            data: volumes,
            barWidth: '60%'
          }
        ]
      };
      if(mainChartInstance.current)
      {
          mainChartInstance.current.setOption(mainOption)
          mainChartInstance.current.resize()//刷新图形，填满整个容器
      }
      if(volumeChartInstance.current)
      {
        volumeChartInstance.current.setOption(volumeOption)
        volumeChartInstance.current.resize()
      }
      
      // 手动触发 resize
      // setTimeout(() => {
      //   mainChartRef.resize();
      //   volumeChartRef.resize();
      // }, 0);
    };
  // 从接口获取分时数据
  const convertTimeData = (day) => {
    try {
      const tickDataInner = JSON.parse(JSON.stringify(tickDataOuter));
      if(day==='1day')
      {
          tickDataInner.ts_code = tickDataOuter.ts_code;
          tickDataInner.data = tickDataOuter.data.slice(-241)
      }

      // console.log('tickDataInner',tickDataInner)
      if (tickDataInner && tickDataInner.data) {
        const times = tickDataInner.data.map(item => item.time);
        const data = tickDataInner.data.map(item => item.price);
        const avgData = tickDataInner.data.map(item => item.avg_price);
        const pre_close = tickDataInner.data[0]?.pre_close;  //获取昨日收盘价，也适用于5日分时
        const volumes = tickDataInner.data.map(item => ({
          value: item.vol,
          itemStyle: { color: item.price >= item.pre_close ? '#ff0000' : '#00ff00' }
        }));

        return { times, data, avgData, volumes, pre_close };
      }
      return { times: [], data: [], avgData: [], volumes: [],pre_close:0 };
    } catch (error) {
      console.error('获取分时数据失败:', error);
      return { times: [], data: [], avgData: [], volumes: [],};
    }
  };

  const handleChartMouseMove = (event) => {
      const rect = mainChartRef.current.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      setCrosshairPosition({ x, y });
      
      // 根据图表类型显示不同的提示信息
      if (currentChartType === '1day' || currentChartType === '5day') {
         const currentTimeChartData = timeChartDataRef.current;
        if(currentTimeChartData)//确保无数据时候无响应
        {
          const { times = [], data = [], avgData = [], volumes = [],pre_close } = currentTimeChartData;
          if (!Array.isArray(times) || !Array.isArray(data) || !Array.isArray(avgData) || !Array.isArray(volumes)) {
            console.error('Invalid data format for time chart');
            return;
          }
          const index = Math.floor((x / rect.width) * times.length);
          if (index >= 0 && index < times.length) {
            const price = data[index];
            const avgPrice = avgData[index];
            const change = ((price - pre_close) / pre_close * 100).toFixed(2);
            setTooltipData({
              time: times[index],
              price: price.toFixed(2),
              avgPrice: avgPrice.toFixed(2),
              change: `${change}%`,
              changeValue: (price - pre_close).toFixed(2),
              type: 'time'
            });
          }
        }
      } else {
        let kdata = dayKData
        if(currentChartType === 'week')
        {
            kdata = weekKData
        }
        else if(currentChartType === 'month')
        {
            kdata = monthKData
        }
        const { data } = convertDayKData(kdata);
        const index = Math.floor((x / rect.width) * data.length);
        if (index >= 0 && index < data.length) {
          const kData = data[index];
          const [open, close, low, high] = kData.value;
          const change = ((close - open) / open * 100).toFixed(2);
          const date = new Date(kData.time);
          const dateStr = echarts.time.format(date, '{yyyy}-{MM}-{dd}', false);
          
          setTooltipData({
            time: dateStr,
            open: open.toFixed(2),
            close: close.toFixed(2),
            high: high.toFixed(2),
            low: low.toFixed(2),
            change: `${change}%`,
            volume: (kData.volume / 10000).toFixed(2) + '万',
            type: 'kline'
          });
        }
      }
    };

    const handleChartMouseLeave = () => {
      setCrosshairPosition(null);
      setTooltipData(null);
    };
  // 图表类型按钮
  const chartTypeButtons = [
    { key: '1day', label: '分时' },
    { key: '5day', label: '5日' },
    { key: 'day', label: '日K' },
    { key: 'week', label: '周K' },
    { key: 'month', label: '月K' }
  ];

  return (
    <div className="main-container">
      <div className="stock-container">
        <div className="chart-tabs">
          {chartTypeButtons.map(button => (
            <button
              key={button.key}
              className={`tab-btn ${currentChartType === button.key ? 'active' : ''}`}
              onClick={() => setCurrentChartType(button.key)}
            >
              {button.label}
            </button>
          ))}
        </div>
        <div className="chart-wrapper" ref={chartWrapperRef}>
          {/* 十字准星线 */}
          {crosshairPosition && (
            <>
              <div 
                className="crosshair-line crosshair-vertical"
                style={{ left: crosshairPosition.x, top: 0 }}
              />
              <div 
                className="crosshair-line crosshair-horizontal"
                style={{ top: crosshairPosition.y, left: 0 }}
              />
            </>
          )}
          
          {/* 工具提示 */}
          {tooltipData && crosshairPosition && (
            <div 
              className="tooltip"
              style={{ 
                left: crosshairPosition.x + 10, 
                top: crosshairPosition.y + 10 
              }}
            >
              {tooltipData.type === 'time' ? (
                <>
                  <div className="tooltip-line"><strong>时间:</strong> {tooltipData.time}</div>
                  <div className="tooltip-line"><strong>价格:</strong> {tooltipData.price}</div>
                  <div className="tooltip-line"><strong>均价:</strong> {tooltipData.avgPrice}</div>
                  <div className="tooltip-line"><strong>涨跌:</strong> {tooltipData.changeValue}</div>
                  <div className="tooltip-line"><strong>涨幅:</strong> {tooltipData.change}</div>
                </>
              ) : (
                <>
                  <div className="tooltip-line"><strong>时间:</strong> {tooltipData.time}</div>
                  <div className="tooltip-line"><strong>开盘:</strong> {tooltipData.open}</div>
                  <div className="tooltip-line"><strong>收盘:</strong> {tooltipData.close}</div>
                  <div className="tooltip-line"><strong>最高:</strong> {tooltipData.high}</div>
                  <div className="tooltip-line"><strong>最低:</strong> {tooltipData.low}</div>
                  <div className="tooltip-line"><strong>涨幅:</strong> {tooltipData.change}</div>
                  <div className="tooltip-line"><strong>成交量:</strong> {tooltipData.volume}</div>
                </>
              )}
            </div>
          )}
          
          {/* 左侧标签 - 分时图显示涨跌幅，K线图隐藏 */}
          <div className="change-labels" id="change-labels">
            {/* 涨跌幅标签将通过JS动态生成 */}
          </div>
          
          <div className="chart-main">
            <div ref={mainChartRef} className="main-chart"></div>
            <div ref={volumeChartRef} className="volume-chart"></div>
          </div>
          
          {/* 右侧标签容器 */}
          <div style={{ display: 'flex', flexDirection: 'column', width: '100px' }}>
            {/* 价格标签 */}
            <div className="price-labels" id="price-labels">
              {/* 价格标签将通过JS动态生成 */}
            </div>
            
            {/* 成交量/成交金额标签 */}
            <div className="volume-labels" id="volume-labels">
              {/* 成交量标签将通过JS动态生成 */}
            </div>
          </div>
        </div>
          
        
      </div>
    
   {/* 右侧信息区域 */}
     <div className="stock-info-panel">
      <div className="stock-info-item">名称: {stockInfo.name}</div>
       <div className="stock-info-item">代码: {stockInfo.ts_code}</div>
       <div className="stock-info-item">最新: {stockInfo.close}</div>
       <div className="stock-info-item">涨幅: {stockInfo.pct_chg}</div>
       <div className="stock-info-item">成交额: {stockInfo.amount}</div>
       <div className="stock-info-item">换手率: {stockInfo.turnover_rate_f}</div>
       <div className="stock-info-item">量比: {stockInfo.volume_ratio}</div>
       <div className="stock-info-item">流通市值: {stockInfo.circ_mv}</div>
       <div className="stock-info-item">总市值: {stockInfo.total_mv}</div>
       <div className="stock-info-item">行业: {stockInfo.industry}</div>
       <div className="stock-info-item">地域: {stockInfo.area}</div>
       <div className="stock-info-item">沪深股通: {stockInfo.is_hs}</div>
       <div className="stock-info-item">市盈率: {stockInfo.pe}</div>
       <div className="stock-info-item">市净率: {stockInfo.pb}</div>
       <div className="stock-info-item">股息率: {stockInfo.dv_ratio}</div>
     </div>
   </div>        
  );
};

export default StockChart;